const express = require('express')
const route = express.Router();
const jwt = require('jsonwebtoken');
const http = require('https');
const qs = require('querystring');
var configs = require('../configs.js');
var db = require('../utils/db');  //数据库管理工具
var qiniu=require('../utils/qiniu');

const wxconfig = configs.wxconfig();



const createToken = (rawData,openid)=>{

    let token = jwt.sign({
        "nickName":rawData.nickName,
        "gender":rawData.gender,
        "language":rawData.language,
        "city":rawData.city,
        "province":rawData.province,
        "country":rawData.country,
    }, openid, {
        expiresIn: 2*60*60   //token过期时间两小时
    });
    return token;
}

route.post('/login',async (_req,_res)=>{

    console.log(_req.body, " 页面传入参数")
    //通过前端的code  和 appid  secret  grant_type  获取 openid  session_key
    // https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
    var data = {
        appid: wxconfig.appid,
        secret: wxconfig.secret,
        js_code: _req.body.code,
        // js_code: _req.query.code,
        grant_type:'authorization_code'
    }
    var content = qs.stringify(data);
    var options = {
        hostname: 'api.weixin.qq.com',
        port: '',
        path: '/sns/jscode2session?' + content,
        method: 'GET' ,
        header: {
            "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
        },
    };

    var req = http.request(options,  function (res) {

        res.on('data', async function (_data) {

            let newdata = JSON.parse(_data.toString());
            console.log(newdata);
            const openid = newdata.openid;
            var user= JSON.parse(_req.body.rawData);
                const token = createToken(_req.body.rawData,openid);
            user.openId=openid;

            var saveUserRes=await db.saveUser(user);
            user=await db.getUserByOpenId(openid);
            if(!user){
                _res.send({status:-1,data:{error:"error"}}).end();
            }else {
                var userToken={
                    userId:user.id,
                    openId:openid,
                    token:token
                };
                var saveTokenRes=await db.saveToken(userToken);
                console.log(saveTokenRes);
                _res.send({status:200,data:{userToken}}).end();
            }

        });

    });

    req.on('error', function (e) {
        console.log('problem with request: ' + e.message);
    });

    req.end();


});


route.get('/checkToken',async (req,res)=>{
    let clienttoken  = JSON.parse(req.query.token);
    var token=await db.getByToken(clienttoken.token);
    if(token){
        //解密token
        jwt.verify(clienttoken.token, token.openId, function (err, decoded) {
            if (err){
                res.send({status:0,data:{errmsg:'token失效'},}).end();
            }else if(decoded){
                res.send({status:200}).end()
            }
        });
    }else {
        res.send({status:0,data:{errmsg:'token失效'}}).end();
    }
});

route.get('/test1',async (req,res)=>{
    var token=qiniu.getUploadToken();
    res.send({uptoken:token}).end();

});




module.exports= route;
